package uqbar.comm.simpleProtocol;

import java.io.OutputStream;

import uqbar.comm.ProgramException;
import uqbar.comm.StringUtils;
import uqbar.comm.protocol.Output;


public class SimpleOutput implements Output {

	private String type;
	private String content;

	public SimpleOutput(final String type, final String content) {
		this.type = type;
		this.content = content;
	}

	public String getType() {
		return this.type;
	}

	public String getContent() {
		return this.content;
	}

	@Override
	public void send(final OutputStream stream) {
		try {
			stream.write(this.getType().getBytes());
			stream.write(this.getContentSizeAsByteArray());
			stream.write(this.getContent().getBytes());
		} catch (Exception e) {
			throw ProgramException.wrap(e);
		}
	}

	protected byte[] getContentSizeAsByteArray() {
		String length = new Integer(this.getContent().length()).toString();
		length = StringUtils.fill(length, 5, '0');
		return length.getBytes();
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + (this.content == null ? 0 : this.content.hashCode());
		result = prime * result + (this.type == null ? 0 : this.type.hashCode());
		return result;
	}

	@Override
	public boolean equals(final Object obj) {
		if (this == obj) {
			return true;
		}
		if (obj == null) {
			return false;
		}
		if (this.getClass() != obj.getClass()) {
			return false;
		}
		SimpleOutput other = (SimpleOutput) obj;
		if (this.content == null) {
			if (other.content != null) {
				return false;
			}
		} else if (!this.content.equals(other.content)) {
			return false;
		}
		if (this.type == null) {
			if (other.type != null) {
				return false;
			}
		} else if (!this.type.equals(other.type)) {
			return false;
		}
		return true;
	}
}
